import React, { useState, useRef, useEffect } from 'react';
import { ChatSession, ChatMessage } from '../../KimiChat';
import './ChatContent.scss';

interface ChatContentProps {
    session: ChatSession | undefined;
    onSendMessage: (content: string) => void;
    isWaitingForResponse: boolean;
    pendingResponses: ChatMessage[];
    onAcceptResponse: (messageId: string) => void;
    onRejectResponse: (messageId: string) => void;
    onAcceptAllResponses: () => void;
    onRejectAllResponses: () => void;
}

const ChatContent: React.FC<ChatContentProps> = ({ 
    session, 
    onSendMessage, 
    isWaitingForResponse, 
    pendingResponses, 
    onAcceptResponse, 
    onRejectResponse,
    onAcceptAllResponses,
    onRejectAllResponses
}) => {
    const [inputValue, setInputValue] = useState('');
    const [isComposing, setIsComposing] = useState(false);
    const messagesEndRef = useRef<HTMLDivElement>(null);
    const textareaRef = useRef<HTMLTextAreaElement>(null);

    const scrollToBottom = () => {
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    };

    useEffect(() => {
        scrollToBottom();
    }, [session?.messages, pendingResponses]);

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        if (inputValue.trim() && !isComposing && !isWaitingForResponse) {
            onSendMessage(inputValue.trim());
            setInputValue('');
            // 重置textarea高度
            if (textareaRef.current) {
                textareaRef.current.style.height = 'auto';
            }
        }
    };

    const handleKeyDown = (e: React.KeyboardEvent) => {
        if (e.key === 'Enter' && !e.shiftKey && !isComposing) {
            e.preventDefault();
            handleSubmit(e);
        }
    };

    const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
        setInputValue(e.target.value);
        
        // 自动调整textarea高度
        const textarea = e.target;
        textarea.style.height = 'auto';
        textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px';
    };

    const formatTime = (date: Date) => {
        return date.toLocaleTimeString('zh-CN', {
            hour: '2-digit',
            minute: '2-digit'
        });
    };

    const renderMessage = (message: ChatMessage) => {
        return (
            <div
                key={message.id}
                className={`chat-message chat-message--${message.type}`}
            >
                <div className="chat-message__avatar">
                    {message.type === 'user' ? (
                        <div className="chat-message__user-avatar">👤</div>
                    ) : (
                        <div className="chat-message__assistant-avatar">🤖</div>
                    )}
                </div>
                <div className="chat-message__content">
                    <div className="chat-message__header">
                        <span className="chat-message__sender">
                            {message.type === 'user' ? '您' : 'Kimi'}
                        </span>
                        <span className="chat-message__time">
                            {formatTime(message.timestamp)}
                        </span>
                    </div>
                    <div className="chat-message__text">
                        {message.content}
                    </div>
                </div>
            </div>
        );
    };
    
    const renderPendingMessage = (message: ChatMessage) => {
        return (
            <div
                key={message.id}
                className="chat-message chat-message--pending"
            >
                <div className="chat-message__avatar">
                    <div className="chat-message__assistant-avatar">🤖</div>
                </div>
                <div className="chat-message__content">
                    <div className="chat-message__header">
                        <span className="chat-message__sender">
                            Kimi (待确认)
                        </span>
                        <span className="chat-message__time">
                            {formatTime(message.timestamp)}
                        </span>
                    </div>
                    <div className="chat-message__text">
                        {message.content}
                    </div>
                    <div className="chat-message__actions">
                        <button 
                            className="chat-message__action-btn chat-message__action-btn--accept"
                            onClick={() => onAcceptResponse(message.id)}
                        >
                            ✓ 采用
                        </button>
                        <button 
                            className="chat-message__action-btn chat-message__action-btn--reject"
                            onClick={() => onRejectResponse(message.id)}
                        >
                            ✗ 放弃
                        </button>
                    </div>
                </div>
            </div>
        );
    };

    if (!session) {
        return (
            <div className="chat-content">
                <div className="chat-content__empty">
                    <div className="chat-content__empty-icon">💭</div>
                    <h3>欢迎使用 Kimi Chat</h3>
                    <p>选择一个对话或创建新对话开始聊天</p>
                    <div className="chat-content__features">
                        <div className="chat-content__feature">
                            <span className="chat-content__feature-icon">📊</span>
                            <span>智能数据分析</span>
                        </div>
                        <div className="chat-content__feature">
                            <span className="chat-content__feature-icon">📈</span>
                            <span>实时图表展示</span>
                        </div>
                        <div className="chat-content__feature">
                            <span className="chat-content__feature-icon">🔍</span>
                            <span>数据筛选排序</span>
                        </div>
                    </div>
                </div>
            </div>
        );
    }

    return (
        <div className="chat-content">
            <div className="chat-content__header">
                <h2 className="chat-content__title">{session.title}</h2>
                <div className="chat-content__meta">
                    {session.messages.length} 条消息
                </div>
            </div>
            
            <div className="chat-content__messages">
                {session.messages.length === 0 && pendingResponses.length === 0 ? (
                    <div className="chat-content__welcome">
                        <div className="chat-content__welcome-icon">👋</div>
                        <p>开始新的对话吧！</p>
                        <p className="chat-content__welcome-tip">输入您的问题，我会为您分析并展示相关数据</p>
                    </div>
                ) : (
                    <>
                        {session.messages.map(renderMessage)}
                        {pendingResponses.map(renderPendingMessage)}
                    </>
                )}
                <div ref={messagesEndRef} />
            </div>
            
            {pendingResponses.length > 0 && (
                <div className="chat-content__pending-actions">
                    <div className="chat-content__pending-info">
                        <span className="chat-content__pending-count">
                            {pendingResponses.length} 条待确认回复
                        </span>
                    </div>
                    <div className="chat-content__pending-buttons">
                        <button 
                            className="chat-content__pending-btn chat-content__pending-btn--accept-all"
                            onClick={onAcceptAllResponses}
                        >
                            ✓ 全部采用
                        </button>
                        <button 
                            className="chat-content__pending-btn chat-content__pending-btn--reject-all"
                            onClick={onRejectAllResponses}
                        >
                            ✗ 全部放弃
                        </button>
                    </div>
                </div>
            )}
            
            <div className="chat-content__input-area">
                <form onSubmit={handleSubmit} className="chat-content__form">
                    <div className="chat-content__input-wrapper">
                        <textarea
                            ref={textareaRef}
                            value={inputValue}
                            onChange={handleInputChange}
                            onKeyDown={handleKeyDown}
                            onCompositionStart={() => setIsComposing(true)}
                            onCompositionEnd={() => setIsComposing(false)}
                            placeholder={isWaitingForResponse ? "等待回复中..." : "输入消息... (Shift + Enter 换行)"}
                            className="chat-content__input"
                            rows={1}
                            disabled={isWaitingForResponse}
                        />
                        <button
                            type="submit"
                            disabled={!inputValue.trim() || isComposing || isWaitingForResponse}
                            className="chat-content__send-btn"
                        >
                            {isWaitingForResponse ? (
                                <div className="chat-content__loading-spinner"></div>
                            ) : (
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                                    <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
                                </svg>
                            )}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
};

export default ChatContent;